package com.haier.cre.commonframe.utils;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.StringUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.nio.channels.FileChannel;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.functions.Consumer;
import rx.functions.Action1;

/**
 * 项目名：CommonLibrary
 * 包 名：com.haier.cre.commonframe.utils
 * 创建人：18002063
 * 日 期：2018/10/16
 * 简 述：公共的工具类
 */
public class CommonUtils {

    // 汉语中数字大写
    private static final String[] CN_UPPER_NUMBER = {"零", "壹", "贰", "叁", "肆",
            "伍", "陆", "柒", "捌", "玖"};

    // 汉语中货币单位大写，这样的设计类似于占位符
    private static final String[] CN_UPPER_MONETRAY_UNIT = {"分", "角", "元",
            "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "兆", "拾",
            "佰", "仟"};

    // 特殊字符：整
    private static final String CN_FULL = "整";

    // 特殊字符：负
    private static final String CN_NEGATIVE = "负";

    // 金额的精度，默认值为2
    private static final int MONEY_PRECISION = 2;

    // 特殊字符：零元整
    private static final String CN_ZEOR_FULL = "零元" + CN_FULL;

    public static final DecimalFormat nf_a = new DecimalFormat("#,##0.00");// amount

    /**
     * 从assets文件中读取文件内容 转换成String
     *
     * @param strAssertFileName assert资源名称
     * @return
     */
    public static String readAssertResource(String strAssertFileName) {
        AssetManager assetManager = UIUtils.getContext().getAssets();
        String strResponse = "";
        try {
            InputStream ims = assetManager.open(strAssertFileName);
            strResponse = ConvertUtils.inputStream2String(ims, "UTF-8");
        } catch (IOException e) {
            //e.printStackTrace();
        }
        return strResponse;
    }

    /**
     * 获取清单文件中的meta-data的value
     *
     * @param context 上下文
     * @param name    meta-data的name
     * @return meta-data的value
     */
    public static String getApplicationMetaValue(Context context, String name) {
        String value = "";
        try {
            ApplicationInfo appInfo = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            value = appInfo.metaData.getString(name);
        } catch (PackageManager.NameNotFoundException e) {
            //e.printStackTrace();
        }
        return value;
    }

    /**
     * 判断传递的值是否为空
     *
     * @param content
     * @return
     */
    public static String judgeISEmpty(String content) {
        if (StringUtils.isEmpty(content)) {
            return "";
        } else {
            return content;
        }
    }

    /**
     * 日期中插入"-"
     *
     * @param dateContent
     * @return
     */
    public static String transDateToShow(String dateContent) {
        if (!StringUtils.isEmpty(dateContent)) {
            if (dateContent.length() == 8) {
                StringBuffer stringBuffer = new StringBuffer(dateContent);
                return stringBuffer.insert(4, "-").insert(7, "-").toString();
            }
        }
        return "";
    }

    /**
     * 获取国籍
     *
     * @return
     */
    public static List<String> getNationality(Context context, String type) {
        try {
            List<String> list = new ArrayList<>();
            InputStreamReader isr = new InputStreamReader(context.getAssets().open("data.json"), "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String line;
            StringBuilder builder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }
            br.close();
            isr.close();
            JSONObject jsonObject = new JSONObject(builder.toString());//builder读取了JSON中的数据。
            JSONArray array = jsonObject.getJSONArray(type);//从JSONObject中取出数组对象
            for (int i = 0; i < array.length(); i++) {
                JSONObject role = array.getJSONObject(i);    //取出数组中的对象
                String name = role.getString("name");
                list.add(name);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    /**
     * 获取名族
     *
     * @return
     */
    public static String getMZ(Context context, String type, String data) {
        try {
            String content = "";
            InputStreamReader isr = new InputStreamReader(context.getAssets().open("data.json"), "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String line;
            StringBuilder builder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }
            br.close();
            isr.close();
            JSONObject jsonObject = new JSONObject(builder.toString());//builder读取了JSON中的数据。
            JSONArray array = jsonObject.getJSONArray("family");//从JSONObject中取出数组对象
            for (int i = 0; i < array.length(); i++) {
                JSONObject role = array.getJSONObject(i);    //取出数组中的对象
                String id = role.getString("id");
                String name = role.getString("name");
                if ("id".equalsIgnoreCase(type)) {
                    if (id.equalsIgnoreCase(data)) {
                        content = name;
                        return content;
                    }
                } else if ("name".equalsIgnoreCase(type)) {
                    if (name.equalsIgnoreCase(data)) {
                        content = id;
                        return content;
                    }
                }
            }
            return "";
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 2013-02-02转换为Calendar
     *
     * @param strDate
     * @return
     */
    public static Calendar strToCalendar(String strDate) {
        Calendar dayc1 = new GregorianCalendar();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date daystart = null; //start_date是类似"2013-02-02"的字符串
        try {
            daystart = df.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        dayc1.setTime(daystart);
        return dayc1;
    }

    /**
     * 获取当前时间
     *
     * @return
     */
    public static Calendar getSystemDateEnd() {
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        SimpleDateFormat formatter_year = new SimpleDateFormat("yyyy ");
        String year_str = formatter_year.format(curDate);
        int year_int = (int) Double.parseDouble(year_str);


        SimpleDateFormat formatter_mouth = new SimpleDateFormat("MM ");
        String mouth_str = formatter_mouth.format(curDate);
        int mouth_int = (int) Double.parseDouble(mouth_str);

        SimpleDateFormat formatter_day = new SimpleDateFormat("dd ");
        String day_str = formatter_day.format(curDate);
        int day_int = (int) Double.parseDouble(day_str);

        Calendar endDate = Calendar.getInstance();
        endDate.set(year_int, mouth_int - 1, day_int);
        return endDate;
    }

    /**
     * 计算两个时间相差多少分钟,返回两个时间差值在几个月区间的标识
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     */
    public static boolean dateCompare(String startTime, String endTime) {
        try {
            //按照传入的格式生成一个simpledateformate对象
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
            long nd = 1000 * 24 * 60 * 60;//一天的毫秒数
            long nh = 1000 * 60 * 60;//一小时的毫秒数
            long nm = 1000 * 60;//一分钟的毫秒数
            long ns = 1000;//一秒钟的毫秒数
            //获得两个时间的毫秒时间差异
            long diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
            long day = diff / nd;//计算差多少天
            long hour = diff % nd / nh;//计算差多少小时
            long min = diff % nd % nh / nm;//计算差多少分钟
            long sec = diff % nd % nh % nm / ns;//计算差多少秒//输出结果
            L.d("DateUtils", "时间相差：" + day + "天" + hour + "小时" + min + "分钟" + sec + "秒。");
            if (diff < 0) {
                return true;
            } else {
                return false;
            }
        } catch (ParseException e) {
            //e.printStackTrace();
            return false;
        }
    }

    /**
     * 判断金额是否大于10000
     *
     * @param numberData
     * @return
     */
    public static boolean isNumberUnit(String numberData) {
        if (!StringUtils.isEmpty(numberData)) {
            double data = Double.parseDouble(numberData);
            if (data < 10000) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    /**
     * 判断金额是否大于10000
     * 转换金额
     *
     * @param numberData
     * @return
     */
    public static String transNumberUnit(String numberData) {
        if (!StringUtils.isEmpty(numberData)) {
            double data = Double.parseDouble(numberData);
            if (data < 10000) {
                return numberData;
            } else {
                double n = (double) data / 10000;
                return n + "";
            }
        } else {
            return "0";
        }
    }

    /**
     * 将手机的分辨率从 dp的单位 转成为 px(像素)
     *
     * @param context
     * @param dpValue
     * @return
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 将手机的分辨率从 px(像素) 的单位 转成为 dp
     *
     * @param context
     * @param pxValue
     * @return
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     * @param pxValue
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @param spValue
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale =
                context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 复制文件（以文件通道的方式）
     *
     * @param s 源文件（如：D:\\test.zip）
     * @param t 目的文件（如：E:\\to.zip）
     */
    public static boolean fileChannelCopy(File s, File t) {
        FileInputStream fi = null;
        FileOutputStream fo = null;
        FileChannel in = null;
        FileChannel out = null;
        boolean result = false;
        try {
            fi = new FileInputStream(s);
            fo = new FileOutputStream(t);
            in = fi.getChannel();// 得到对应的文件通道
            out = fo.getChannel();// 得到对应的文件通道
            in.transferTo(0, in.size(), out);// 连接两个通道，并且从in通道读取，然后写入out通道
            result = true;
        } catch (IOException e) {
            //e.printStackTrace();
            result = false;
        } finally {
            try {
                if (fi != null)
                    fi.close();
                if (in != null)
                    in.close();
                if (fo != null)
                    fo.close();
                if (out != null)
                    out.close();
            } catch (IOException e) {
                //e.printStackTrace();
                result = false;
            }
        }
        return result;
    }

    /**
     * 去除字符串中的所有空格以及回车符
     *
     * @param str
     * @return
     */
    public static String delBlank_Aarriage(String str) {
        Pattern p = Pattern.compile("\\s*|\n");
        Matcher m = p.matcher(str);
        return m.replaceAll("");
    }

    /**
     * 根据响应的组建View和Activity隐藏软键盘
     *
     * @param view     响应的View
     * @param activity 当前Activity
     */
    public static void hideInputMethod(View view, Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null && imm.isActive()) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 根据响应的组建View和Activity打开软键盘
     *
     * @param view     响应的View,接收键盘输入内容的View
     * @param activity 当前Activity
     */
    public static void showInputMethod(View view, Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
        }
    }

    /**
     * 汉字过滤
     *
     * @param ori
     * @return
     */
    public static String hanziGuolv(String ori) {
        String reg = "[^\u4e00-\u9fa5]";
        Pattern pat = Pattern.compile(reg);
        Matcher mat = pat.matcher(ori);
        String str = mat.replaceAll("");
        return str;
    }

    static int yourChose = -1;

    /**
     * 调用拨打电话功能，直接拨打
     *
     * @param context 上下文
     * @param number  号码
     */
    public static void doCall(final Context context, final String number) {
        RxPermissions rxPermissions = null;
        try {
            rxPermissions = new RxPermissions((FragmentActivity) context);
            rxPermissions.request(Manifest.permission.CALL_PHONE).subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) {
                    if (aBoolean) {
                        if (number != null) {
                            if (number.contains("/")) {
                                /**
                                 * 单选对话框
                                 */
                                final String[] mList = number.split("/");
                                yourChose = 0;
                                AlertDialog.Builder sinChosDia = new AlertDialog.Builder(context);
                                sinChosDia.setTitle("请选择要拨打的号码");
                                sinChosDia.setSingleChoiceItems(mList, 0, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        // TODO Auto-generated method stub
                                        yourChose = which;

                                    }
                                });
                                sinChosDia.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        // TODO Auto-generated method stub
                                        if (yourChose != -1) {
                                            String num = mList[yourChose];
                                            if (num.length() == 8) {
                                                //                                                num = Constant.NUM_HK+num;
                                            }
                                            takeTel(context, num);
                                        } else {
                                            Toast.makeText(context, "请选择要拨打的号码!", Toast.LENGTH_LONG).show();
                                        }
                                    }
                                });
                                sinChosDia.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                                sinChosDia.create().show();
                            } else {
                                /**
                                 * 对话框
                                 */
                                AlertDialog.Builder normalDia = new AlertDialog.Builder(context);
                                normalDia.setMessage("是否拨打" + number);

                                normalDia.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        takeTel(context, number);
                                    }
                                });
                                normalDia.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                                normalDia.create().show();
                            }
                        } else {
                            T.showToast("请到权限管理中开启相对应的手机权限", T.WARNING);
                            getAppDetailSettingIntent(context);
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void takeTel(Context context, String number) {
        Uri uri = Uri.parse("tel:" + number);
        Intent intent = new Intent(Intent.ACTION_DIAL, uri);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        context.startActivity(intent);
    }

    /**
     * 调用拨打电话功能，跳转到打电话界面
     *
     * @param context 上下文
     * @param number  号码
     * @param type    类型  1香港手机,2香港座机,3内地手机,4内地座机
     */
    public static void doCallType(final Context context, final String number, final int type) {
        RxPermissions rxPermissions = null;
        try {
            rxPermissions = new RxPermissions((FragmentActivity) context);
            rxPermissions.request(Manifest.permission.CALL_PHONE).subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) {
                    if (aBoolean) {
                        String phoneNumber = number;
                        if (type == 1) {
                            phoneNumber = "00852" + number;
                        } else if (type == 2) {

                        } else if (type == 3) {
                            phoneNumber = "+86" + number;
                        } else if (type == 4) {
                            phoneNumber = "+86" + number;
                        } else {

                        }
                        Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber));//跳转到拨号界面，同时传递电话号码
                        context.startActivity(dialIntent);
                    } else {
                        T.showToast("请到权限管理中开启相对应的手机权限", T.WARNING);
                        getAppDetailSettingIntent(context);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 调用发送短信功能
     *
     * @param context 上下文
     * @param number  号码
     * @param content 内容
     */
    public static void openSMS(final Context context, final String number, final String content) {
        RxPermissions rxPermissions = null;
        try {
            rxPermissions = new RxPermissions((FragmentActivity) context);
            rxPermissions.request(Manifest.permission.CALL_PHONE).subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) {
                    if (aBoolean) {
                        Uri uri = Uri.parse("smsto:" + number);
                        Intent it = new Intent(Intent.ACTION_SENDTO, uri);
                        it.putExtra("sms_body", content);
                        it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(it);
                    } else {
                        T.showToast("请到权限管理中开启相对应的手机权限", T.WARNING);
                        getAppDetailSettingIntent(context);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 调用发送邮件功能
     *
     * @param context 上下文
     * @param subject 标题
     * @param content 内容
     */
    public static void openEmail(final Context context, final String[] toPerson, final String subject, final String content) {
        //        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult((Activity) context,
        //                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, new PermissionsResultAction() {
        //                    @Override
        //                    public void onGranted() {
        //
        //                    }
        //
        //                    @Override
        //                    public void onDenied(String permission) {
        //                        Toast.makeText(context,
        //                                "Sorry, we need the " + permission + " to do that",
        //                                Toast.LENGTH_SHORT).show();
        //                    }
        //                });
        Intent data = new Intent(Intent.ACTION_SEND);
        data.putExtra(Intent.EXTRA_EMAIL, toPerson);
        //        data.setData(Uri.parse("mailto:"+toPerson));
        data.putExtra(Intent.EXTRA_SUBJECT, subject + "");
        data.putExtra(Intent.EXTRA_TEXT, content + "");
        //        data.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
        data.setType("application/octet-stream");
        data.setPackage("com.android.email");
        context.startActivity(data);
    }

    /**
     * 跳转到权限设置界面
     */
    public static void getAppDetailSettingIntent(Context context) {

        //        // vivo 点击设置图标>加速白名单>我的app
        //        //      点击软件管理>软件管理权限>软件>我的app>信任该软件
        //        Intent appIntent = context.getPackageManager().getLaunchIntentForPackage("com.iqoo.secure");
        //        if (appIntent != null) {
        //            context.startActivity(appIntent);
        //            floatingView = new SettingFloatingView(this, "SETTING", (), 0);
        //            floatingView.createFloatingView();
        //            return;
        //        }
        //
        //        // oppo 点击设置图标>应用权限管理>按应用程序管理>我的app>我信任该应用
        //        //      点击权限隐私>自启动管理>我的app
        //        appIntent = context.getPackageManager().getLaunchIntentForPackage("com.oppo.safe");
        //        if (appIntent != null) {
        //            context.startActivity(appIntent);
        //            floatingView = new SettingFloatingView(this, "SETTING", getApplication(), 1);
        //            floatingView.createFloatingView();
        //            return;
        //        }

        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", AppUtils.getAppPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", AppUtils.getAppPackageName());
        }
        context.startActivity(intent);
    }

    /**
     * 删除指定目录下文件及目录 （递归删除）
     *
     * @param filePath
     * @param deleteThisPath
     * @return
     */
    public static void deleteFolderFile(String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {
                    // 处理目录
                    File files[] = file.listFiles();
                    for (int i = 0; i < files.length; i++)
                        deleteFolderFile(files[i].getAbsolutePath(), true);
                }
                if (deleteThisPath) {
                    if (!file.isDirectory())
                        file.delete(); // 如果是文件，删除
                    else if (file.listFiles().length == 0) // 目录
                        file.delete(); // 目录下没有文件或者目录，删除
                }
            } catch (Exception e) {
                //e.printStackTrace();
            }
        }
    }

    /**
     * 删除指定文件
     *
     * @param filePath
     * @return
     */
    public static void deleteFile(String filePath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.exists() && file.length() > 0) {
                    file.delete();
                }
            } catch (Exception e) {
                //e.printStackTrace();
            }
        }
    }

    /**
     * 格式化文件大小单位
     *
     * @param size
     * @return
     */
    public static String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1)
            return size + "Byte(s)";

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB";
        }

        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }

    // 将金额转换为人民币大写
    public static String number2AmountCapital(BigDecimal numberOfMoney) {
        String str = "";
        try {
            StringBuffer sb = new StringBuffer();
            // -1, 0, or 1 as the value of this BigDecimal is negative, zero, or
            // positive.
            int signum = numberOfMoney.signum();
            // 零元整的情况
            if (signum == 0) {
                return CN_ZEOR_FULL;
            }
            // 这里会进行金额的四舍五入
            long number = numberOfMoney.movePointRight(MONEY_PRECISION)
                    .setScale(0, 4).abs().longValue();
            // 得到小数点后两位值
            long scale = number % 100;
            int numUnit = 0;
            int numIndex = 0;
            boolean getZero = false;
            // 判断最后两位数，一共有四中情况：00 = 0, 01 = 1, 10, 11
            if (!(scale > 0)) {
                numIndex = 2;
                number = number / 100;
                getZero = true;
            }
            if ((scale > 0) && (!(scale % 10 > 0))) {
                numIndex = 1;
                number = number / 10;
                getZero = true;
            }
            int zeroSize = 0;
            while (true) {
                if (number <= 0) {
                    break;
                }
                // 每次获取到最后一个数
                numUnit = (int) (number % 10);
                if (numUnit > 0) {
                    if ((numIndex == 9) && (zeroSize >= 3)) {
                        sb.insert(0, CN_UPPER_MONETRAY_UNIT[6]);
                    }
                    if ((numIndex == 13) && (zeroSize >= 3)) {
                        sb.insert(0, CN_UPPER_MONETRAY_UNIT[10]);
                    }
                    sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);
                    sb.insert(0, CN_UPPER_NUMBER[numUnit]);
                    getZero = false;
                    zeroSize = 0;
                } else {
                    ++zeroSize;
                    if (!(getZero)) {
                        sb.insert(0, CN_UPPER_NUMBER[numUnit]);
                    }
                    if (numIndex == 2) {
                        if (number > 0) {
                            sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);
                        }
                    } else if (((numIndex - 2) % 4 == 0) && (number % 1000 > 0)) {
                        sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);
                    }
                    getZero = true;
                }
                // 让number每次都去掉最后一个数
                number = number / 10;
                ++numIndex;
            }
            // 如果signum == -1，则说明输入的数字为负数，就在最前面追加特殊字符：负
            if (signum == -1) {
                sb.insert(0, CN_NEGATIVE);
            }
            // 输入的数字小数点后两位为"00"的情况，则要在最后追加特殊字符：整
            if (!(scale > 0)) {
                sb.append(CN_FULL);
            }
            str = sb.toString();
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return str;
    }

    /**
     * 判断字符串是否包含中文
     *
     * @param str
     * @return
     */
    public static boolean isContainChinese(String str) {

        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    /**
     * 判断程序是否有某个权限
     *
     * @param context
     * @param permName
     * @return
     */
    public static boolean checkPermission(Context context, String permName) {
        PackageManager pm = context.getPackageManager();
        if (PackageManager.PERMISSION_GRANTED == pm.checkPermission(permName, "hk.com.cre.portal.mobile")) {
            return true;
        } else {
            //PackageManager.PERMISSION_DENIED == pm.checkPermission(permName, pkgName)
            return false;
        }
    }

    /**
     * 判断手机号码格式是否正确
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 测量文本 text 所占的长度
     */
    public static float getTextWidth(String text, float textSize) {
        Paint mTextPaint = new Paint();
        mTextPaint.setTextSize(textSize); // 指定字体大小
        //Typeface font = Typeface.create(Typeface.MONOSPACE,Typeface.NORMAL);
        //   mTextPaint.setTypeface(font);
        //mTextPaint.setFakeBoldText(true); // 粗体
        return mTextPaint.measureText(text);
    }

}
